package x.ovo.wechat.bot;

import cn.hutool.core.util.StrUtil;
import cn.hutool.db.nosql.redis.RedisDS;
import lombok.Cleanup;
import lombok.extern.slf4j.Slf4j;
import redis.clients.jedis.Jedis;
import x.ovo.wechat.bot.common.entity.event.MessageEvent;
import x.ovo.wechat.bot.common.entity.message.TextMessage;
import x.ovo.wechat.bot.common.event.Event;
import x.ovo.wechat.bot.common.event.EventListener;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 关键字监控侦听器
 *
 * @author ovo on 2024/05/14.
 * @since 1.0.0
 */
@Slf4j(topic = "关键词监控")
public class KeywordListener extends EventListener<MessageEvent<TextMessage>> {

    static final RedisDS ds = RedisDS.create();
    public static final String KEYWORD_MAP_KEY = "keyword:map";
    public static final String KEYWORD_KEY_PREFIX = "keyword::{}";
    public static final Map<String, List<String>> KEYWORD_MAP = new HashMap<>(16);

    public KeywordListener() {
        Jedis jedis = ds.getJedis();
        Map<String, List<String>> map = jedis.hgetAll(KEYWORD_MAP_KEY).entrySet().stream()
                .collect(Collectors.toMap(Map.Entry::getKey, entry -> Arrays.asList(entry.getValue().replace("[", "").replace("]", "").split(", "))));
        KEYWORD_MAP.putAll(map);
        jedis.close();
    }

    @Override
    public boolean support(Event<?> event) {
        return event instanceof MessageEvent
                && event.getSource() instanceof TextMessage
                && StrUtil.isNotBlank(((MessageEvent<?>) event).getContent())
                && ((TextMessage) event.getSource()).isGroup();
    }

    @Override
    public void onEvent(MessageEvent<TextMessage> event) {
        @Cleanup Jedis jedis = ds.getJedis();
        TextMessage message = event.getSource();
        String content = event.getContent();

        KEYWORD_MAP.computeIfAbsent(message.getFromUser().getNickName(), k -> new ArrayList<>()).stream()
                .filter(content::contains)
                .findFirst()
                .ifPresent(keyword -> {
                    log.info("收到关键词消息: [{}] {}", keyword, content);
                    jedis.hincrBy(StrUtil.format(KEYWORD_KEY_PREFIX, message.getFromUser().getNickName()), keyword, 1);
                    if ("traveler".equals(message.getMember().getNickName())) {
                        this.context.getApi().sendText(message.getFromUser().getUserName(), StrUtil.format("《{}》", keyword));
                    }
                });
    }
}
